<template>
	<div>
		<div flex style="height: 100%;">
			<base-layout :buttonShow="false" style="width:260px; " :isPage="false" :buttonList="buttonTreeList"
				@onFuncBtn="handleTreeThings" :showTitle="false" :defaultButtonSwitch="false">
				<div slot="main" style="height: 100%;overflow-y: auto;border-right: 1px solid #dfe6ec;">
					<base-tree :isCenter="false" :isSaveBtn="false" :Allshow="false" :showCheckbox="false"
						:menuData="menuData" :showTitle="false" @handleNodeClick="orangClick"></base-tree>
				</div>
			</base-layout>
			<base-layout :buttonList="buttonList" :isPage="true" @onFuncBtn="handleDialog" ref="supplierTablePage"
				style="flex: 1;" :showTitle="false" @pageChange="onPageChange">
				<div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
					<base-table :border="true" :showIndex="false" :slotrow="true" :tableHeight="tableHeight"
						@onFunc="onFunc" :funData="funData" :tabLoading.sync="tabLoading" :tableData="tableData"
						:tableColumn="tableColumn" @radioChange="supplierRadioChange" ref="tableData">
						<template v-slot:option="{ row }">
							<el-radio v-model="radioSupplier" :label="row.$index">
								<span></span>
							</el-radio>
						</template>
						<template v-slot:companyCount="{ row }">
							<span @click="handleclickOpenChecklist(row.row)"
								style="width:100%;cursor: pointer;color:#3ca2e1">{{
									row.row.companyCount
								}}</span>
						</template>
					</base-table>
				</div>
			</base-layout>
		</div>
		<!-- S 新增 编辑弹窗 -->
		<base-dialog :dialogVisible.sync="fileManagementDialog" :closeModal="false" :footerShow="true" :title="dialogType"
			width="95%" top="3vh" @handleConfirmClick="handleAddDialogDetails">
			<base-form :formRow="supplierFormList" :isFunBtn="isFunBtn" ref="supplierForm" @onSelect="onSelect"
				@elDialogClick="elDialogClick" :rules="rules"></base-form>
			<supplier-details ref="supplierUserDetails"></supplier-details>
			<attachment-details ref="custmanAtt"></attachment-details>
		</base-dialog>
		<!-- E 新增弹窗 -->


		<!-- S 分管部门 -->
		<base-organization ref="baseOrganization" :menuData="OrganTreeData"
			@handleConfirmClick="handleOrganTreeDetails"></base-organization>
		<!-- E 分管部门 -->

		<!-- S 组织机构树弹窗 -->
		<base-dialog :dialogVisible.sync="treeManagementDialog" :closeModal="false" :footerShow="true"
			:title="treeDialogType" width="55%" top="20vh" @handleConfirmClick="handleTreeDialogDetails">
			<base-form :formRow="treeDialogListRow" :isFunBtn="isFunBtn" :rules="treeDialogRules"
				ref="treeDataRef"></base-form>
		</base-dialog>
		<!-- E 组织机构树弹窗 -->

		<!-- S 查看 -->
		<base-dialog :dialogVisible.sync="showManagementDialog" :closeModal="false" :footerShow="true" title="查看"
			width="75%" top="3vh" @handleConfirmClick="handleShowDialogDetails">
			<look-form :formRow="showFormColumn" :spanNumber="spanNumber" :ruleForm="showFormData"></look-form>
			<br />
			<base-table :border="true" :showIndex="false" :tabLoading.sync="tabLoading" :slotrow="false"
				:tableData="detailedTableData" :tableColumn="detailedTableColumn">
				<!--  序号  -->
				<template v-slot:index="{ row }">
					<span>{{ row.index + 1 }}</span>
				</template>
				<template v-slot:isdefault="{ row }">
					<span>{{ row.isdefault == 1 ? "是" : "否" }}</span>
				</template>

			</base-table>
			<br />
			<base-table :border="true" :showIndex="false" :tabLoading.sync="tabLoading" :slotrow="false"
				:tableData="enclosureTableData" :tableColumn="enclosureTableColumn">
				<!--  序号  -->
				<template v-slot:index="{ row }">
					<span>{{ row.index + 1 }}</span>
				</template>
				<template v-slot:sa_UploadDateTime="{ row }">{{ formatTime(row.sa_UploadDateTime) }}
				</template>
			</base-table>
		</base-dialog>
		<!-- E 查看 -->

		<!-- S 选择所属公司弹窗 -->
		<base-dialog :dialogVisible.sync="showOperateDialog" :closeModal="false" :footerShow="true" title="选择所属公司"
			width="45%" height="75vh" top="20vh" @handleConfirmClick="handleOperateDialogDetails">
			<el-checkbox-group v-model="checkList" style="display: flex;flex-wrap: wrap;">
				<el-checkbox v-for="(item, index) in labelList" :key="index" style="width: 28%;padding: 10px;" :label="item.companyName
					" :checked="item.checked" @change="changeCheck(item, index)"></el-checkbox>
			</el-checkbox-group>
		</base-dialog>
		<!-- E 选择所属公司弹窗 -->

		<!-- S 所属公司查看弹窗 -->
		<base-dialog :dialogVisible.sync="showCompanyDialog" :closeModal="false" :footerShow="false" title="所属公司"
			height="400px" width="15%" top="20vh">
			<div class="company-list" v-for="(item, index) in openList" :key="index">{{ item.companyName }}</div>
		</base-dialog>
		<!-- E 所属公司查看弹窗 -->

	</div>
</template>
<script>
// 组件
import baseLayout from "@/components/base/baseLayout";
import baseTable from "@/components/base/baseTable";
import baseDialog from "@/components/base/BaseNewDialog";
import baseForm from "@/components/base/baseNewForm";
import baseTree from "@/components/base/BaseMenuTree";
import lookForm from "@/components/base/baselookForm/index.vue";
import { getCompanyId } from '@/utils/auth'

// 表头数据
import supplierConfig from "./supplierConfig";
// 表格数据
import {
	vendorGetBillList, //供应商表格数据
	getUserMenuList, //供应商组织树
	GetListByparentID, //省市县
	GetOrganTree, //分管部门
	vendorGetBillData, //详细信息
	vendorSaveData, //供应商保存
	vendorDelData, //供应商删除
	classifySaveCusData,
	classifyDelCusData,
	GetCusEditList, SaveVenDate, GetDistribute
} from "@/api/apis/fileManagement";
import supplierDetails from "./supplierDetails.vue";
import attachmentDetails from "./attachmentDetails.vue";
import baseOrganization from "@/components/base/baseOrganization/index.vue";
import {
	OrganGetCompany
} from '@/api/apis/organization'
import { UploadList, } from "@/api/apis/auth.js";

export default {
	name: "supplierManagement",
	components: {
		baseLayout,
		baseTable,
		baseDialog,
		baseForm,
		baseOrganization,
		baseTree,
		supplierDetails,
		attachmentDetails,
		lookForm,
	},
	data() {
		return {
			mainColor: "#f8f8f8",
			menuData: [], //菜单树数据
			funData: [{
				color: '#3CA2E1',
				text: '选择所属公司'
			},],
			buttonList: [
				{
					icon: "el-icon-reading",
					menuName: "查看",
				},
			], //按钮组
			buttonTreeList: [{
				icon: "el-icon-plus",
			},
			{
				icon: "el-icon-edit",
			},
			{
				icon: "el-icon-delete",
				type: "danger",
			},
			], //树
			rules: supplierConfig.rules,
			treeDialogRules: supplierConfig.treeDialogRules,
			treeManagementDialog: false,
			treeDialogType: "新增",
			tabLoading: false,
			tableHeight: "67vh",
			tableData: [], //表格数据
			dialogType: "新增", //表格类型
			fileManagementDialog: false, //控制新增编辑弹窗是否打开
			Ddk_DataDicKindID: "", //组织
			selectTableData: [], //当前选中的数据
			supplierFormList: supplierConfig.supplierFormList, //新增表单
			isFunBtn: false,
			treeNodeSelected: {
				//当前选中的树节点
				venClassify: "",
				venClassifyName: "",
			},
			OrganTreeDialogVisible: false, //分管部门弹窗
			OrganTreeData: [], //分管部门
			treeHeight: "350px",
			organizationForm: {}, //选择组织机构
			selectTableData: {}, //当前选中的数据
			radioSupplier: false,
			showManagementDialog: false, //查看弹窗
			showFormColumn: supplierConfig.showFormColumn,
			spanNumber: 8,
			showFormData: {},
			detailedTableColumn: supplierConfig.supplierAddColumn,
			detailedTableData: [],
			enclosureTableColumn: supplierConfig.enclosureTableColumn,
			enclosureTableData: [],
			pageModel: { //分页
				page: 1,
				limit: 20,
			},
			CreatePersonID: '', //创建人id
			showOperateDialog: false,//操作弹窗
			showCompanyDialog: false,//所属公司查看弹窗
			labelList: [],//
			checkList: [],
			checkListId: [],
			openList: [],
			appendix: [],

		};
	},
	computed: {
		//供应商档案列表表头数据
		tableColumn() {
			return supplierConfig.supplierTableColumn;
		},
		treeDialogListRow() {
			return supplierConfig.treeFormData;
		},
	},
	mounted() {
		// 初始化
		this.initPage()
	},
	methods: {
		formatTime(row) {
			return row && row.substring(0, 10);
		},
		initPage() {
			this.CreatePersonID = this.$store.state.user.info.UserID
			this.getMenuList();
			this.getTableData();
			this.getListByparent();
			this.getCompanyList()

		},
		//点击查看所属公司列表
		async handleclickOpenChecklist(row) {
			if (row.companyCount > 0) {
				this.getCheckListData(row)
				this.showCompanyDialog = true
			} else {
				this.getCheckListData(row)
			}
		},
		onFunc(index, row) {
			// console.log(row);
			if (row.companyCount > 0) {
				this.getCheckListData(row)
			} else {
				this.checkList = []
			}
			this.showOperateDialog = true
		},
		// 表格数据
		async getTableData() {
			this.tabLoading = true;
			let params = {
				...this.pageModel,
				CodeOrName: "",
				cusClassify: this.treeNodeSelected.venClassify, //当前点击分类id
				Sequence: "",
				SequenceName: "",
			};
			let res = await vendorGetBillList(params);
			if (res.code == 1) {
				this.$nextTick(() => {
					this.tableData = res.data[1];
					this.$refs.tableData.clearRadioIndex()
					this.selectTableData = {}
					this.$refs.supplierTablePage.setPageTotal(res.data[0]);
				});
				this.tabLoading = false;
			}
		},
		// 组织列表
		async getMenuList() {
			let res = await getUserMenuList({});
			// 请求数据成功
			if (res.code === 1) {
				this.menuData = res.data[0]
			}
		},
		// 树节点被点击
		orangClick(data) {
			this.treeNodeSelected.venClassifyName = data.label;
			this.treeNodeSelected.venClassify = data.id;
			this.getTableData();
		},
		// 行单机
		supplierRadioChange(val) {
			this.selectTableData = val;
			this.radioSupplier = val.index;
		},
		// 分页
		onPageChange(model) {
			this.pageModel.page = model.page
			this.pageModel.limit = model.limit
			this.getTableData()
		},
		// 监听分管部门输入框
		elDialogClick(row, index, indexRow) {
			if (row.prop === "orgainName") {
				this.$refs.baseOrganization.dialogVisible = true
				this.getOrganTreeList();
			}
		},
		//省市县选择器选中
		onSelect(val, index, indexRow) {
			if (indexRow == 0) {
				this.supplierFormList[3].elCol[1].options = [];
				this.supplierFormList[3].elCol[2].options = [];
				this.$refs.supplierForm.ruleForm.city = "";
				this.$refs.supplierForm.ruleForm.county = "";
			}
			if (indexRow == 1) {
				this.supplierFormList[3].elCol[2].options = [];
				this.$refs.supplierForm.ruleForm.county = "";
			}
			this.getListByparent(val, indexRow);
		},
		// 省市县下拉框
		async getListByparent(id, indexRow) {
			let params = {
				id: id ? id : "-1",
			};
			let res = await GetListByparentID(params);
			if (res.code === 1) {
				if (!id) {
					//省
					this.supplierFormList[3].elCol[0].options = res.data[0]
				} else {
					if (indexRow == 0) {
						//市
						this.supplierFormList[3].elCol[1].options = res.data[0]
					} //县
					if (indexRow == 1) {
						this.supplierFormList[3].elCol[2].options = res.data[0]
					}
				}
			}
		},
		// 获取附件列表
		async UploadList1(item) {
			if (JSON.stringify(item) != '[]') {
				let list = item.split("'")
				this.appendix = []
				list.forEach(el => {
					if (el != "" && el != ', ') {
						this.appendix.push(el)
					}
				});
				const res = await UploadList({
					page: "1", //当前页码
					limit: "10", //每页显示多少
					billid: "", //业务单据ID
					filesIDs: this.appendix, //附件ID
				})
				if (res.success == "true") {
					this.enclosureTableData = res.data[1]
				}
			}
		},
		// 弹窗 - 分管部门组织机构树
		async getOrganTreeList() {
			let params = {
				// CompanyID: "1",
				CompanyID: this.$store.state.user.companyID ? this.$store.state.user.companyID : getCompanyId()
			};
			let res = await GetOrganTree(params);
			if (res.code == 1) {
				this.OrganTreeData = JSON.parse(res.data[0]);
			}
		},
		// 分管部门确定按钮
		handleOrganTreeDetails(val) {
			this.$refs.supplierForm.getField("orgainName", val.label);
			this.$refs.supplierForm.getField("organID", val.id);
			this.$refs.baseOrganization.dialogVisible = false
		},
		// 获取公司列表
		async getCompanyList() {
			let res = await OrganGetCompany({})
			if (res.code == 1) {
				this.labelList = res.data[0]
			}
		},
		//查询已分配公司列表
		async getCheckListData(row) {
			let params = {
				baseKind: row.venClassify, //客户种类
				baseID: row.billid //
			}
			let res = await GetDistribute(params)
			if (res.code == 1) {
				this.openList = res.data[0]
				this.checkList = this.openList.map(item => item.companyName)
			}
		},
		//选择所属公司弹窗确认
		async handleOperateDialogDetails() {
			//过滤并组成新数组
			const checkListId = this.labelList.filter(item => this.checkList.includes(item.companyName)).map(item => item.companyID);
			let params = {
				baseKind: this.selectTableData.venClassify,//客户分类id
				baseID: this.selectTableData.billid, //唯一billid
				companyID: checkListId
			}
			let res = await SaveVenDate(params)
			if (res.code === 1) {
				this.$vmNews('分配所属成功', 'success')
				this.showOperateDialog = false
				this.checkLis = []
				this.getTableData()
			}
		},
		changeCheck(item) {
		},
		// 获取当前行详情数据
		async getrowDetails(val) {
			let params = {
				id: val.billid,
				op: "",
				code: val.venCode
			};
			let res = await vendorGetBillData(params);
			if (res.code === 1) {
				let data = res.data;
				this.$nextTick(() => {
					if (data[0].province != "" && data[0].province != null) {
						data[0].province = parseInt(data[0].province);
					}
					if (data[0].city != "" && data[0].city != null) {
						data[0].city = parseInt(data[0].city);
					}
					if (data[0].county != "" && data[0].county != null) {
						data[0].county = parseInt(data[0].county);
					}
					// 编辑
					if (this.fileManagementDialog === true) {
						this.getListByparent(data[0].province, 0)
						this.getListByparent(data[0].city, 1)
						this.$refs.supplierForm.choiceAssignment(data[0]);
						this.$refs.supplierUserDetails.tableData = data[1];
						this.$refs.custmanAtt.$refs.uploadAttachments.UploadList1(data[2])

					}
					// 查看
					if (this.showManagementDialog === true) {
						this.showFormData = data[0];
						this.detailedTableData = data[1];
						this.UploadList1(data[2])

					}
				});
			}
		},
		handleDialog(item) {
			// 新增
			if (item.menuName == "新增") {
				this.dialogType = "新增";
				if (this.treeNodeSelected.venClassify === "") {
					this.$vmNews("请选择分类", "warning");
					return;
				} else {
					this.fileManagementDialog = true;
					this.$nextTick(() => {
						this.$refs.supplierForm.incomingParameters(this.treeNodeSelected);
					});
				}
			}
			// 编辑
			if (item.menuName == "编辑") {
				this.dialogType = "编辑";
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews("请选择一条数据!", "warning");
					return;
				} else {
					this.fileManagementDialog = true;
					this.$nextTick(() => {
						// let billid = this.selectTableData.billid
						let val = this.selectTableData;
						this.getrowDetails(val)
					})
				}
			}
			// 删除
			if (item.menuName == "删除") {
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews("请选择一条数据!", "warning");
					return;
				} else {
					this.$delConfirm().then(() => {
						let billid = this.selectTableData.billid;
						this.removeTableItem(billid);
					})
				}
			}
			// 查看
			if (item.menuName == "查看") {
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews("请选择一条数据!", "warning");
					return;
				} else {
					this.showManagementDialog = true;
					let val = this.selectTableData;
					this.getrowDetails(val);
				}
			}
		},
		// 保存
		handleAddDialogDetails() {
			this.$refs.supplierForm.$refs['ruleForm'].validate((valid) => {
				if (valid) {
					this.save()
				} else {
					this.$message({
						message: '请输入必填项',
						type: 'warning'
					});
					return
				}
			})
		},
		async save() {
			let params = {
				dataMain: {
					Billid: this.dialogType == "新增" ?
						"00000000-0000-0000-0000-000000000000" :
						this.selectTableData.billid,
					...this.$refs.supplierForm.ruleForm,
					CreatePersonID: this.CreatePersonID,
				},
				base_Vendor_LinkMan: this.$refs.supplierUserDetails.tableData,
				attIDS: this.$refs.custmanAtt.$refs.uploadAttachments.appendix.join()
			};
			let res = await vendorSaveData(params);
			if (res.code == 1) {
				this.$vmNews("保存成功", "success");
				this.fileManagementDialog = false;

				this.getTableData();
			}

		},
		// 删除
		async removeTableItem(billid) {
			let params = {
				id: billid,
			};
			let res = await vendorDelData(params);
			if (res.code === 1) {
				this.$vmNews("删除成功！", "success");
				this.getTableData();
			}
		},
		// 处理组织机构树事件
		handleTreeThings(item) {
			// 新增
			if (item.icon === "el-icon-plus") {
				this.treeDialogType = "新增";
				if (this.treeNodeSelected.venClassify === "") {
					this.$vmNews("请选择分类", "warning");
					return;
				} else {
					this.treeManagementDialog = true;
					let param = {
						parentID: this.treeNodeSelected.venClassify,
						codename: this.treeNodeSelected.venClassifyName,
					};
					this.$nextTick(() => {
						this.$refs.treeDataRef.incomingParameters(param);
					});
				}
			}
			// 编辑
			if (item.icon === "el-icon-edit") {
				this.treeDialogType = "编辑";
				if (this.treeNodeSelected.venClassify === "") {
					this.$vmNews("请选择分类", "warning");
					return;
				} else {
					this.treeManagementDialog = true;
					this.$nextTick(() => {
						let id = this.treeNodeSelected.venClassify;
						this.getDetailsTreeNodeData(id);
					});
				}
			}
			// 删除
			if (item.icon === "el-icon-delete") {
				if (this.treeNodeSelected.venClassify === "") {
					this.$vmNews("请选择分类", "warning");
					return;
				} else {
					this.$delConfirm().then(() => {
						let id = this.treeNodeSelected.venClassify;
						this.deleteTreeDialogDetails(id);
					})
				}
			}
		},
		// 选中节点的详细信息
		async getDetailsTreeNodeData(id) {
			let param = {
				id: id,
			};
			let res = await GetCusEditList(param);
			if (res.code === 1) {
				this.$refs.treeDataRef.incomingParameters(res.data[1]);
			}
		},
		// 组织机构树提交保存
		handleTreeDialogDetails() {
			this.$refs.treeDataRef.$refs['ruleForm'].validate((valid) => {
				if (valid) { this.saveTreeDialogDetails() }
			})
		},
		async saveTreeDialogDetails() {
			let params = {
				dataMain: this.$refs.treeDataRef.ruleForm,
			};
			let res = await classifySaveCusData(params);
			if (res.code === 1) {
				this.$vmNews("保存成功", "success");
				this.treeManagementDialog = false;
				this.getMenuList();
				this.treeNodeSelected.venClassify = ''
				this.treeNodeSelected.venClassifyName = ''
			}
		},
		// 组织机构树删除
		async deleteTreeDialogDetails(id) {
			let param = {
				id: id,
			};
			let res = await classifyDelCusData(param);
			if (res.code === 1) {
				this.$vmNews("删除成功", "success");
				this.getMenuList();
				this.treeNodeSelected.venClassify = ''
				this.treeNodeSelected.venClassifyName = ''
			}
		},
		// 查看弹窗 确认事件
		handleShowDialogDetails() {
			this.showManagementDialog = false;
		},
	},
	watch: {
		// 树弹窗
		treeManagementDialog: {
			deep: true,
			handler(newValue, oldValue) {
				if (newValue === false) {
					// 重置表单
					this.$refs.treeDataRef.resetFields("ruleForm");
				}
			},
		},
		// 新增编辑弹窗
		fileManagementDialog: {
			deep: true,
			handler(newValue, oldValue) {
				if (newValue === false) {
					// 重置表单
					this.$refs.supplierForm.resetFields("ruleForm");
					this.$refs.supplierUserDetails.tableData = [];
					this.$refs.custmanAtt.$refs.uploadAttachments.tableData = []
					this.$refs.supplierTablePage.pageClear()
				}
			},
		},
	},
};
</script>

<style scoped>
.organizationBody {
	display: flex;
	justify-content: space-evenly;
	background-color: #f2f3f4;
	padding: 10px;
}

::v-deep .el-form-item__error {
	padding: 0;
	top: 83%
}

.company-list {
	display: flex;
	flex-direction: column;
	padding: 5px;
	align-items: center;
}
</style>
.supplierFormList
